<template>
  <div class="comment-container">
    <!-- 评论发表区域 -->
    <div class="comment-form-section">
      <div class="form-header">
        <i class="icon-chat"></i>
        <span>发表评论</span>
      </div>
      
      <!-- 头像选择 -->
      <div class="avatar-selection">
        <h4>选择头像</h4>
        <div class="avatar-grid">
          <div 
            v-for="(image, i) in avatarImages" 
            :key="i"
            :class="['avatar-option', { active: activeNum === i }]"
            @click="activeAvatar(i, image.url)"
          >
            <el-image :src="image.url" fit="cover"></el-image>
          </div>
        </div>
      </div>
      
      <!-- 表单输入 -->
      <div class="form-inputs">
        <div class="input-row">
          <el-input 
            v-model="commentator" 
            placeholder="您的名称" 
            class="form-input"
            prefix-icon="User"
          />
          <el-input 
            v-model="email" 
            placeholder="邮箱地址" 
            class="form-input"
            prefix-icon="Message"
          />
        </div>
        <div class="textarea-container">
          <el-input 
            v-model="commentText" 
            type="textarea"
            :rows="4"
            placeholder="写下你的评论..."
            class="comment-textarea"
            @keyup.enter="addComment(0,0,0)"
          />
          <button class="submit-btn" @click="addComment(0,0,0)">
            <i class="icon-chat"></i>
            发表评论
          </button>
        </div>
      </div>
    </div>
    
    <!-- 分割线 -->
    <div class="comment-divider">
      <div class="divider-line"></div>
      <div class="divider-line"></div>
    </div>
    
    <!-- 评论列表区域 -->
    <div class="comments-section">
      <div class="comments-header">
        <i class="icon-chat"></i>
        <span>评论列表</span>
        <span class="comment-count">({{ comments.list.length }})</span>
      </div>

      <div v-for="(comment, f_index) in comments.list" :key="comment.id" class="comment-item">
        <!-- 一级评论内容 -->
        <div 
          class="comment-main"
          @mouseover="showButton(f_index, 0, true)" 
          @mouseleave="hideButton(f_index, 0, true)"
        >
          <div class="comment-user">
            <el-avatar :size="48" :src="comment.websiteUrl" />
            <div class="user-info">
              <div class="user-name">{{ comment.commentator }}</div>
              <div class="comment-meta">
                <span><i class="icon-shijian1"></i>{{ comment.timeAgo }}</span>
                <span><i class="icon-icon"></i>{{ comment.ipSource }}</span>
              </div>
            </div>
            <button 
              v-show="comment.showCommentButton" 
              class="reply-btn"
              @click="addReply(comment.id, comment.commentator)"
            >
              <i class="icon-chat"></i>
              回复
            </button>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
        </div>

        <!-- 二级评论（回复）内容 -->
        <div v-if="comment.replies && comment.replies.length > 0" class="replies-container">
          <div 
            v-for="(reply, index) in comment.replies" 
            :key="reply.id" 
            class="reply-item"
            @mouseover="showButton(index, f_index, false)" 
            @mouseleave="hideButton(index, f_index, false)"
          >
            <div class="reply-user">
              <el-avatar :size="36" :src="reply.websiteUrl" />
              <div class="user-info">
                <div class="user-name">{{ reply.commentator }}</div>
                <div class="comment-meta">
                  <span><i class="icon-shijian1"></i>{{ reply.timeAgo }}</span>
                  <span><i class="icon-icon"></i>{{ reply.ipSource }}</span>
                </div>
              </div>
              <button 
                v-show="reply.showCommentButton" 
                class="reply-btn small"
                @click="addReply(comment.id, reply.commentator)"
              >
                <i class="icon-chat"></i>
                回复
              </button>
            </div>
            <div class="reply-content">
              <span class="mention">@{{ reply.toUser }}</span>
              {{ reply.content }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onBeforeMount, onMounted, onUpdated, reactive, ref, watch} from 'vue';
import {add, getCommentsByBlogId} from "../api/comment.js";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";


const comment = reactive({
  blogId: 0,
  commentator: "",
  email: "",
  content: "",
  parentId: 0,
  level: 1,
  toUser: "",
  websiteUrl: "http://img.linzhongyue.cn/kubawang.png",
})

const comments = reactive({
  list: [],
});

const commentText = ref('');
const commentator = ref('');
const email = ref('');
const avatar = ref('');
const activeNum = ref(0);
const replyText = ref('');
const avatarImages = ref([
  {url: "http://img.linzhongyue.cn/kubawang.png"},
  {url: "http://img.linzhongyue.cn/ggbond.png"},
  {url: "http://img.linzhongyue.cn/xiaodaidai.png"},
  {url: "http://img.linzhongyue.cn/jiaozi.jpg"},
]);

const articleElement = defineProps({
  // 接收传值   此处的father就是父组件的自定义名称
  blogId: {
    type: Number,  // 数据类型
    default: 0  // 未传值时的默认值
  }
})

const emit = defineEmits(['updateCommentCount'])

watch(articleElement, (nweProps) => {
  console.log(articleElement.blogId)
  getComments();
})

const showButton = (index,f_index,flag) => {
  // true 就是一级评论
  // false 就是二级评论
  if(flag){
    comments.list[index].showCommentButton = true;
  }else{
    comments.list[f_index].replies[index].showCommentButton = true;
  }
};

const hideButton = (index,f_index,flag) => {
  // true 就是一级评论
  // false 就是二级评论
  if(flag){
    comments.list[index].showCommentButton = false;
  }else{
    comments.list[f_index].replies[index].showCommentButton = false;
  }
};

// 获取所有评论
const getComments = () => {
  getCommentsByBlogId(articleElement.blogId).then((res) => {
    if (res.code == '200' || res.code == 200) {
      comments.list = res.data;
      // 计算总评论数量（包括回复）
      let totalCount = 0;
      comments.list.forEach(comment => {
        totalCount++; // 主评论
        if (comment.replies && comment.replies.length > 0) {
          totalCount += comment.replies.length; // 回复数量
        }
      });
      // 通知父组件更新评论数量
      emit('updateCommentCount', totalCount);
    }
  })
};

// 添加评论 父ID，等级，回复的用户
const addComment = (p_id,l,t_u) => {


  if (commentText.value.trim() !== '' && commentator.value.trim() !== '' && email.value.trim() !== '') {
    // 设置评论
    comment.commentator = commentator.value;
    comment.email = email.value;
    comment.content = commentText.value.trim();
    comment.blogId = articleElement.blogId;
    if(p_id !== 0){
      comment.parentId = p_id;
      comment.level = l;
      comment.toUser = t_u;
    }

    add(comment).then((res) => {
      // 添加成功
      if (res.code === '200' || res.code === 200) {
        ElNotification({
          title: 'success',
          message: res.data,
          type: 'success',
        })
        commentText.value = "";
        getComments();
      } else {
        ElNotification({
          title: 'error',
          message: res.msg,
          type: 'error',
        })

      }
    })
  } else {
    ElNotification({
      title: 'error',
      message: '主体信息和评论内容不能为空',
      type: 'error',
    })
  }


  // if (commentText.value.trim() !== '') {
  //   comments.push({
  //     id: comments.length + 1,
  //     content: commentText.value.trim(),
  //     email: email.value,
  //     commentator: commentator.value,
  //     replies: []
  //   });
  //   commentText.value = '';
  // }
};

const addReply = (commentId,f_commentator) => {
  if (commentator.value.trim() !== '' && email.value.trim() !== '') {
    ElMessageBox.prompt('回复评论：', {
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      inputPlaceholder: "@" + f_commentator
    }).then(({ value }) => {
      commentText.value = value
      addComment(commentId,2,f_commentator);
    })
  }else{
    ElNotification({
      title: 'error',
      message: '主体信息和评论内容不能为空',
      type: 'error',
    })
  }
};

const activeAvatar = (i,url)=>{
  activeNum.value = i;
  comment.websiteUrl = url
}

</script>

<style scoped lang="scss">
@import '@/assets/styles/variables.scss';

.comment-container {
  margin-top: 20px;
}

/* 评论发表区域 */
.comment-form-section {
  background: var(--bg-card);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(227, 242, 253, 0.3);
}

.form-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.form-header i {
  font-size: 20px;
  color: var(--primary-color);
}

.form-header span {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.avatar-selection {
  margin-bottom: 20px;
}

.avatar-selection h4 {
  color: var(--text-secondary);
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
}

.avatar-grid {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.avatar-option {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 3px solid transparent;
}

.avatar-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.avatar-option.active {
  border-color: var(--primary-color);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.avatar-option .el-image {
  width: 100%;
  height: 100%;
}

.input-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-input {
  flex: 1;
}

.textarea-container {
  position: relative;
}

.comment-textarea {
  margin-bottom: 12px;
}

.submit-btn {
  background: var(--gradient-primary);
  color: white;
  border: none;
  border-radius: 12px;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.submit-btn:active {
  transform: translateY(0);
}

.submit-btn i {
  font-size: 16px;
}

/* 分割线样式 */
.comment-divider {
  display: flex;
  align-items: center;
  margin: 40px 0 20px;
  gap: 20px;
}

.divider-line {
  flex: 1;
  height: 2px;
  background: linear-gradient(90deg, transparent 0%, var(--border-color) 50%, transparent 100%);
}

/* 评论列表区域 */
.comments-section {
  /* 移除背景和边框样式 */
}

.comments-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f0f0;
}

.comments-header i {
  font-size: 20px;
  color: var(--primary-color);
}

.comments-header span {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.comment-count {
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 400;
}

.comment-item {
  margin-bottom: 24px;
}

.comment-item:last-child {
  margin-bottom: 0;
}

.comment-main {
  padding: 20px;
  background: var(--bg-secondary);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.comment-main:hover {
  background: var(--bg-muted);
  transform: translateX(4px);
}

.comment-user {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 4px;
}

.comment-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: var(--text-secondary);
}

.comment-meta span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.comment-meta i {
  font-size: 12px;
}

.reply-btn {
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 6px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0;
  transform: translateX(10px);
}

.reply-btn.small {
  padding: 4px 8px;
  font-size: 11px;
}

.reply-btn:hover {
  background: var(--primary-dark);
  transform: translateX(0) translateY(-1px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.reply-btn i {
  font-size: 12px;
}

.comment-main:hover .reply-btn,
.reply-item:hover .reply-btn {
  opacity: 1;
  transform: translateX(0);
}

.comment-content {
  color: var(--text-primary);
  line-height: 1.6;
  font-size: 14px;
  padding: 12px 0;
  margin-left: 60px;
}

/* 回复区域 */
.replies-container {
  margin-top: 16px;
  margin-left: 40px;
  padding-left: 20px;
  border-left: 3px solid #e3f2fd;
}

.reply-item {
  padding: 16px;
  background: var(--bg-card);
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
}

.reply-item:last-child {
  margin-bottom: 0;
}

.reply-item:hover {
  background: var(--bg-secondary);
  border-color: var(--border-color-light);
  transform: translateX(4px);
}

.reply-user {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 8px;
}

.reply-user .user-info {
  flex: 1;
}

.reply-user .user-name {
  font-size: 14px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 2px;
}

.reply-user .comment-meta {
  display: flex;
  gap: 12px;
  font-size: 11px;
  color: var(--text-secondary);
}

.reply-user .comment-meta span {
  display: flex;
  align-items: center;
  gap: 3px;
}

.reply-user .comment-meta i {
  font-size: 11px;
}

.reply-content {
  color: var(--text-primary);
  line-height: 1.6;
  font-size: 13px;
  margin-left: 46px;
}

.mention {
  color: var(--primary-color);
  font-weight: 600;
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .input-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .avatar-grid {
    justify-content: center;
  }
  
  .comment-content {
    margin-left: 0;
  }
  
  .replies-container {
    margin-left: 20px;
    padding-left: 12px;
  }
  
  .reply-content {
    margin-left: 0;
  }
}
</style>
